package tech.mhuang.pacebox.springboot.autoconfiguration.trace.okhttp;

import io.opentracing.Tracer;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import tech.mhuang.pacebox.springboot.autoconfiguration.ConfigConsts;
import tech.mhuang.pacebox.springboot.core.okhttp.OkhttpClientUtil;

import java.util.regex.Pattern;

/**
 * okhttp埋点配置
 *
 * @author mhuang
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(value = TraceOkHttpProperties.class)
@ConditionalOnProperty(prefix = ConfigConsts.TRACE_OKHTTP, name = ConfigConsts.ENABLE, havingValue = ConfigConsts.TRUE, matchIfMissing = true)
public class TraceOkHttpConfiguration {

    public final Tracer tracer;
    public final TraceOkHttpProperties properties;

    public TraceOkHttpConfiguration(Tracer tracer, TraceOkHttpProperties properties) {
        this.tracer = tracer;
        this.properties = properties;
    }

    @Primary
    @Bean
    public OkHttpClient.Builder okHttpClientBuilder() {
        return OkhttpClientUtil.genOkHttpClient(properties.getType(), properties.getProxyHost(), properties.getProxyPort(),
                properties.getCertPath(), properties.getCertPass(), properties.getTrustManager(),
                new TraceOkHttpInterceptor(tracer, Pattern.compile(properties.getSkipPattern())));
    }

}